import base64
import urllib
import requests
import os
import sys
import json

API_KEY = "Vyy9pBG5oQGkPOqZfB8ZhXqS"
SECRET_KEY = "3vYFdL8NYxqsi6rfwqfUBwot1ZqaBEKm"


# 入库菜品识别
def main(path):
    url = (
        "https://aip.baidubce.com/rest/2.0/image-classify/v1/realtime_search/dish/search?access_token="
        + get_access_token()
    )

    # image 可以通过 get_file_content_as_base64("C:\fakepath\salad.jpg",True) 方法获取
    payload = "image="
    payload += get_file_content_as_base64(path, True)
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    response = requests.request("POST", url, headers=headers, data=payload)
    # 解析JSON数据为Python字典和列表
    data_dict = json.loads(response.text)
    result_list = data_dict["result"]
    num = 0
    for dish in result_list[0]["dishes"]:
        # 获取到预测的置信度
        score = dish["score"]
        # 当置信度大于某个值才会返回
        if float(score) >= 0.5 and num < 3:
            # 将string解析成对象
            foodData = json.loads(dish["brief"])
            print(foodData.get("name"))
            print(foodData.get("label"))
            print(foodData.get("calorie"))
            num = num + 1
        else:
            return


def get_file_content_as_base64(path, urlencoded=True):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content


def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY,
    }
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == "__main__":
    photoURL = sys.argv[1]
    photoURL = os.path.abspath(".") + "/api/target/classes/static" + photoURL
    main(photoURL)
